/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
  Text,
  useTheme,
  Container,
  Button,
  SuffixInput,
  IconArrowRight,
  Input,
  Select,
  InputLine, LineColumn,
  CommitInput, CheckSwitch, InputDatalist,
} from "customize-easy-ui-component";
import { UnitOrChoose } from "../../unit/UnitOrChoose";
import { DialogEnterReturn } from "../../context/DialogEnterReturn";
//import queryString from "querystring";
import {主结构形式, 安全状况等级} from "../../device/edit/容器";
import { TransparentInput} from "../../comp/base";
import { 注登状态s, } from "../../device/edit/CommnBase";
import {AdminunitChoose} from "../../common/geo/AdminunitChoose";
import {ChooseUnit} from "../../unit/ChooseUnit";

const queryString = require('query-string');
export const 计费管材料=['钢制','PE管'];
export const 管道敷设式=['埋地','架空','埋地+架空','无','其它'];  //计费字段！

export const 管道级别=['GA1','GA2','GB1','GB2','GC1','GC2','GC3','GD1','GD2'];
//export const 使用状态=['NOTINUSE','USE','STOP','DISCARD','DEMOLISH','MOVEOUT','DELETE','REMOVESUPV','USENOTREG'];
//【特别注意】按照序号对照转换！。 Enum模式(数据库实际是Byte的,Graphql实际是标识符字符串)列表所对应的中文描述：
//export const 使用状态文=[];
export const 使用状态s=[['NOTINUSE','未投入使用'],['USE','在用'],['STOP','停用'],['DISCARD','报废'],['DEMOLISH','拆除'],['MOVEOUT','迁出'],
                  ['DELETE','垃圾数据'],['REMOVESUPV','删除(移除监察)'],['USENOTREG','在用未注册']];
export const eqpUseStateMap = new Map();
使用状态s.map(([enumt,desc],i) => (eqpUseStateMap.set(enumt, desc)) );


interface 管道单元props {
  id?: string;
  readOnly?: boolean;
  editable?: boolean;
  //当前设备数据(确认修改之后)
  eqp?:any;
  //去修改设备数据
  //setEqp:  React.Dispatch<React.SetStateAction<any>>;
  //graphQL的变更执行回调函数 (...args: any[]) => any
  mutationFunc: (...args: any[]) => any;
}
/**管道长度 LENGTH 不应该编辑和输入，其实是统计数。
 * 设计单位 DESIGN_UNT_NAME:在公用部分中（只能选择一个单位）；
 *对管道来说 设计证书编号 不一定是 设计许可证编号；
 *【特殊处理!】装置名称: 已经移交到公用的设备名称字段titl 互换含义。这里添加svp[管道设备名]来存储旧的字段；
 * todo: 单元所在区域 UNIT_AREA_COD ? UNIT_AREA_NAME?还未处理：编辑需要选择关联；
 * 监检报告下检日期： 删掉!；
 * [关联Isp选择] 年检报告 定检检验报告 监检报告
 * */
export const 管道单元: React.FunctionComponent<管道单元props> = ({
       readOnly,
       id,
       editable,
       eqp=null,    //从好几代祖先前的DetailedGuide在graphQL获得后端服务器数据层层传递下来的。
       mutationFunc,  //传递编辑保存回调用
     }) =>
{
  //const qs= queryString.parse(window.location.search);
  const theme = useTheme();
  const {save, field}= window.history.state?.state??{};      //通用伪对话框传递格式field=上次跳转目标选择字段。
  //初始化编辑器的关联对象编辑模式映射字段：【graphQL输入不能直接挪用输出的数据模型啊】编辑显示要统一化成输入模式。
  //const edt = save?  save : eqp;
  const edt = save?  save : {...eqp,
    desu:{id:eqp.desu?.id, name: eqp.desu?.company? eqp.desu?.company?.name : eqp.desu?.person?.name},
    insu:{id:eqp.insu?.id, name: eqp.insu?.company? eqp.insu?.company?.name : eqp.insu?.person?.name}
  };

  //console.log("管道单元管理 007 deqp=" ,eqp,"edt=", edt);

  const [name, setName] = React.useState(edt.name);
  const [leng, setLeng] = React.useState(edt.leng);
  //编辑层desu的数据形式是输入参数，首先从输出字段倒腾用以适应输入的形式qs?.desu{id,name}; 输出是对象关联的模型数据edt.desu。
  //从伪对话框保存的状态?save.恢复
  const [desu, setDesu] = React.useState(save? save.desu : edt.desu);
  const [insu, setInsu] = React.useState(save? save.insu : edt.insu);

  const [insd, setInsd] = React.useState(edt.insd);
  const [used, setUsed] = React.useState(edt.used);
  const [mdi, setMdi] = React.useState(edt.mdi);
  const [matr, setMatr] = React.useState(edt.matr);
  const [start, setStart] = React.useState(edt.start);
  const [stop, setStop] = React.useState(edt.stop);
  const [dia, setDia] = React.useState(edt.dia);
  const [thik, setThik] = React.useState(edt.thik);
  const [safe, setSafe] = React.useState(edt.safe);
  const [lay, setLay] = React.useState(edt.lay);
  const [level, setLevel] = React.useState(edt.level);
  const [proj, setProj] = React.useState(edt.proj);
  const [nxtd1, setNxtd1] = React.useState(edt.nxtd1);
  const [nxtd2, setNxtd2] = React.useState(edt.nxtd2);
  const [ust, setUst] = React.useState(edt.ust);
  const [ad, setAd] = React.useState(edt.ad);

  const  svp = edt?.svp;
  const [规格, set规格] = React.useState(svp?.规格);
  const [设温, set设温] = React.useState(svp?.设温);
  const [设压, set设压] = React.useState(svp?.设压);
  const [焊数, set焊数] = React.useState(svp?.焊数);
  //const [管料, set管料] = React.useState(svp?.管料);
  const [监下, set监下] = React.useState(svp?.监下);
  const [腐蚀, set腐蚀] = React.useState(svp?.腐蚀);
  const [材料, set材料] = React.useState(svp?.材料);
  const [直径, set直径] = React.useState(svp?.直径);

  const  pa = edt?.pa;
  const [工压, set工压] = React.useState(pa?.工压);
  const [试压, set试压] = React.useState(pa?.试压);
  const [工温, set工温] = React.useState(pa?.工温);
  const [防腐材, set防腐材] = React.useState(pa?.防腐材);
  const [沥青级, set沥青级] = React.useState(pa?.沥青级);
  const [防腐厚, set防腐厚] = React.useState(pa?.防腐厚);
  const [工介, set工介] = React.useState(pa?.工介);
  const [实用时, set实用时] = React.useState(pa?.实用时);
  const [绝材, set绝材] = React.useState(pa?.绝材);
  const [绝厚, set绝厚] = React.useState(pa?.绝厚);
  const [保数, set保数] = React.useState(pa?.保数);
  const [备注, set备注] = React.useState(pa?.备注);
  const [图号, set图号] = React.useState(pa?.图号);

  //数据库只需要ID就够, desu数据形式要{id,name}，保存发送接口函数时还会再映射的: desu=>desu.id;
  async function confirmation() {
    const newdat={ ...eqp,
      name,leng,desu,insu,insd,used,mdi,matr,start,stop,
      dia,thik,safe,lay,level,proj,nxtd1,nxtd2,ust,ad,
      svp: {
        规格,设压,设温,焊数,监下,腐蚀,材料,直径,
        }
      ,
      pa: {
        工压,试压,工温,防腐材,沥青级,防腐厚,工介,实用时,绝材,
        绝厚,保数,备注,图号,
        }

    };

    return newdat;
  }


  return (
    <div
      css={{
        [theme.mediaQueries.md]: {
          height: "auto",
          display: "block"
        }
      }}
    >
      <hr/>
      <Text
        css={{
          flex: 1,
          textAlign: "center",
          [theme.mediaQueries.md]: {
            textAlign: "left"
          }
        }}
        wrap={false}
        variant="h5"
        gutter={false}
      >
        {eqp.cod} 管道单元的技术参数
      </Text>

      <div
        css={{
          flex: 1,
          [theme.mediaQueries.md]: {
            flex: "none"
          }
        }}
      >
        <div>
          <Container>
            <div
              css={{
                paddingTop: theme.spaces.lg,
                paddingBottom: theme.spaces.lg
              }}
            >

            <Text variant="h5">管道单元的参数</Text>
            <LineColumn >
              <InputLine label={`管道名称:`}>
                <CommitInput  value={ name || ''}  onSave={txt => setName(txt||undefined) } />
              </InputLine>
              <InputLine label={`管道起点:`}>
                <CommitInput  value={ start || ''}  onSave={txt => setStart(txt||undefined) } />
              </InputLine>
              <InputLine label={`管道止点:`}>
                <CommitInput  value={ stop || ''}  onSave={txt => setStop(txt||undefined) } />
              </InputLine>
              <InputLine label={`工程名称:`}>
                <CommitInput  value={ proj || ''}  onSave={txt => setProj( txt||undefined ) } />
              </InputLine>
              <InputLine label={`管道规格:`}>
                <CommitInput  value={ 规格 || ''}  onSave={txt => set规格( txt||undefined ) } />
              </InputLine>
              <InputLine label={`管道长度:`}>
                <SuffixInput  onSave={txt=> setLeng(txt||undefined)}
                       type="number"  value={ leng || ''}>m</SuffixInput>
              </InputLine>
              <InputLine label={`设计单位:`}>
                <ChooseUnit id={desu?.id} name={desu?.name}  field={'desu'}
                            autoFocus={field==='desu'}
                            onCancel={() => { setDesu(undefined) }}
                            onDialog={async () => { return await confirmation() } }
                />
              </InputLine>
              <InputLine label={`安装单位:`}>
                <ChooseUnit id={insu?.id} name={insu?.name}  field={'insu'}
                            autoFocus={field==='insu'}
                            onCancel={() => { setInsu(undefined) }}
                            onDialog={async () => { return await confirmation() } }
                />
              </InputLine>
              <InputLine label={`安装年月:`}>
                <Input type='date'  value={ insd  || ''}
                       onChange={e => setInsd( e.currentTarget.value||undefined ) } />
              </InputLine>
              <InputLine label={`投用年月:`}>
                <Input type='date'  value={ used  || ''}
                       onChange={e => setUsed( e.currentTarget.value||undefined ) } />
              </InputLine>
              <InputLine label={`设计介质:`}>
                <CommitInput  value={ mdi || ''}  onSave={txt => setMdi(txt||undefined) } />
              </InputLine>
              <InputLine label={`管道材料(计费):`}>
                <Select inputSize="md"  value={ matr || ''}
                        onChange={e => setMatr( e.currentTarget.value||undefined ) } >
                  <option></option>
                  { 计费管材料.map((one,i) => (<option key={i}>{one}</option> )) } </Select>
              </InputLine>
              <InputLine label={`管道材料(管子材料牌号):`}>
                <CommitInput  value={ 材料 || ''}  onSave={txt => set材料(txt||undefined) } />
              </InputLine>
              {/*<InputLine label={`管子材料牌号:`}>
                <CommitInput  value={ 管料 || ''}  onSave={txt => set管料(txt||undefined) } />
              </InputLine>*/}
              <InputLine label={`设计压力:`}>
                <SuffixInput  onSave={txt=> set设压(txt||undefined)}
                          value={ 设压 || ''}>Mpa</SuffixInput>
              </InputLine>
              <InputLine label={`工作压力:`}>
                <SuffixInput  onSave={txt=> set工压(txt||undefined)}
                          value={ 工压 || ''}>Mpa</SuffixInput>
              </InputLine>
              <InputLine label={`试验压力:`}>
                <SuffixInput onSave={txt=> set试压(txt||undefined)}
                              value={ 试压 || ''}>Mpa</SuffixInput>
              </InputLine>
              <InputLine label={`设计温度:`}>
                <SuffixInput onSave={txt=> set设温(txt||undefined)}
                             value={ 设温 || ''}>℃</SuffixInput>
              </InputLine>
              <InputLine label={`工作温度:`}>
                <SuffixInput onSave={txt=> set工温(txt||undefined)}
                             value={ 工温 || ''}>℃</SuffixInput>
              </InputLine>
              <InputLine label={`公称直径(计费):`}>
                <SuffixInput  onSave={txt=> setDia(txt||undefined)}
                              type="number"  value={ dia || ''}>mm</SuffixInput>
              </InputLine>
              <InputLine label={`公称直径:`}>
                <CommitInput  value={ 直径 || ''}  onSave={txt => set直径(txt||undefined) } />
              </InputLine>
              <InputLine label={`公称壁厚:`}>
                <SuffixInput  onSave={txt=> setThik(txt||undefined)}
                              value={ thik || ''}>mm</SuffixInput>
              </InputLine>
              <InputLine label={`腐蚀裕量:`}>
                <CommitInput  value={ 腐蚀 || ''}  onSave={txt => set腐蚀(txt||undefined) } />
              </InputLine>
              <InputLine label={`防腐层材料:`}>
                <CommitInput  value={ 防腐材 || ''}  onSave={txt => set防腐材(txt||undefined) } />
              </InputLine>
              <InputLine label={`防腐层沥青等级:`}>
                <CommitInput  value={ 沥青级 || ''}  onSave={txt => set沥青级(txt||undefined) } />
              </InputLine>
              <InputLine label={`防腐层厚度:`}>
                <SuffixInput  onSave={txt=> set防腐厚(txt||undefined)}
                               value={ 防腐厚 || ''}>mm</SuffixInput>
              </InputLine>
              <InputLine label={`工作介质:`}>
                <CommitInput  value={ 工介 || ''}  onSave={txt => set工介(txt||undefined) } />
              </InputLine>
              <InputLine label={`安全状况等级:`}>
                <InputDatalist value={ safe || ''} datalist={安全状况等级}
                               onListChange={v => setSafe(v ||undefined)} />
                {/*<Select inputSize="md"  value={ safe || ''}
                        onChange={e => setSafe( e.currentTarget.value||undefined ) } >
                  <option></option>
                  { 安全状况等级.map((one,i) => (<option key={i}>{one}</option> )) } </Select>*/}
              </InputLine>
              <InputLine label={`敷设方式:`}>
                <Select inputSize="md"  value={ lay || ''}
                        onChange={e => setLay( e.currentTarget.value||undefined ) } >
                  <option></option>
                  { 管道敷设式.map((one,i) => (<option key={i}>{one}</option> )) } </Select>
              </InputLine>
              <InputLine label={`实际使用时间:`}>
                <CommitInput  value={ 实用时 || ''}  onSave={txt => set实用时(txt||undefined) } />
              </InputLine>
              <InputLine label={`绝热层材料:`}>
                <CommitInput  value={ 绝材 || ''}  onSave={txt => set绝材(txt||undefined) } />
              </InputLine>
              <InputLine label={`绝热层厚度:`}>
                <SuffixInput  onSave={txt=> set绝厚(txt||undefined)}
                              value={ 绝厚 || ''}>mm</SuffixInput>
              </InputLine>
              <InputLine label={`对接焊口数量:`}>
                <CommitInput  value={ 焊数 || ''}  onSave={txt => set焊数(txt||undefined) } />
              </InputLine>
              <InputLine label={`管道级别:`}>
                <Select inputSize="md"  value={ level || ''}
                        onChange={e => setLevel( e.currentTarget.value||undefined ) } >
                  <option></option>
                  { 管道级别.map((one,i) => (<option key={i}>{one}</option> )) } </Select>
              </InputLine>
              <InputLine label={`安全保护装置数量:`}>
                <CommitInput  value={ 保数 || ''}  onSave={txt => set保数(txt||undefined) } />
              </InputLine>
              <InputLine label={`备注:`}>
                <CommitInput  value={ 备注 || ''}  onSave={txt => set备注(txt||undefined) } />
              </InputLine>
              <InputLine label={`图号:`}>
                <CommitInput  value={ 图号 || ''}  onSave={txt => set图号(txt||undefined) } />
              </InputLine>
              <InputLine label={`单元所在区域(点击进入选择):`}>
                <AdminunitChoose  name={ad?.name}   setEditorVar={setAd}
                                  pos={ad}  onCancel={() => { setAd(undefined) }} />
              </InputLine>
              <InputLine label={`注册日期:`}>
                <Input type='date'  value={ edt.regd  || ''}
                     readOnly={true}  onChange={e => 0 } />
              </InputLine>
              <InputLine label={`注册状态:`}>
                <Select inputSize="md"  aria-readonly={true}   defaultValue={ edt.reg || ''}  >
                  { 注登状态s.map(([enumv,title],i) => (<option key={i} value={enumv}>{title}</option> )) } </Select>
              </InputLine>
              <InputLine label={`使用状态:`}>
                <Select inputSize="md"  value={ ust || ''}
                        onChange={e => setUst( e.currentTarget.value||undefined ) } >
                  { 使用状态s.map(([enumv,title],i) => (<option key={i} value={enumv}>{title}</option> )) } </Select>
              </InputLine>
            </LineColumn>

              <Text variant="h5">检验相关信息</Text>
              <LineColumn >
                <InputLine label={`年检报告编号:`}>
                  <TransparentInput readOnly value={eqp.isp1?.no ||''} />
                </InputLine>
                <InputLine label={`年检日期:`}>
                  <TransparentInput type='date' readOnly value={eqp.isp1?.ispDate ||''} />
                </InputLine>
                <InputLine label={`年检结论:`}>
                  <TransparentInput readOnly value={eqp.isp1?.conclusion ||''} />
                </InputLine>
                <InputLine label={`定检检验报告编号:`}>
                  <TransparentInput readOnly value={eqp.isp2?.no ||''} />
                </InputLine>
                <InputLine label={`定检日期:`}>
                  <TransparentInput type='date' readOnly value={eqp.isp2?.ispDate ||''} />
                </InputLine>
                <InputLine label={`定检结论:`}>
                  <TransparentInput readOnly value={eqp.isp2?.conclusion ||''} />
                </InputLine>
                <InputLine label={`监检报告编号:`}>
                  <TransparentInput readOnly value={eqp.ispsv?.no ||''} />
                </InputLine>
                <InputLine label={`监检日期:`}>
                  <TransparentInput type='date' readOnly value={eqp.ispsv?.ispDate ||''} />
                </InputLine>
                <InputLine label={`监检结论:`}>
                  <TransparentInput readOnly value={eqp.ispsv?.conclusion ||''} />
                </InputLine>
                <InputLine label={`监检报告下检日期:`}>
                  <Input type='date' readOnly={true}  value={ 监下  || ''}
                         onChange={e => set监下( e.currentTarget.value||undefined ) } />
                </InputLine>
                <InputLine label={`下次年检日期:`}>
                  <Input type='date'  value={ nxtd1  || ''}
                         onChange={e => setNxtd1( e.currentTarget.value||undefined ) } />
                </InputLine>
                <InputLine label={`定检下检日期:`}>
                  <Input type='date'  value={ nxtd2  || ''}
                         onChange={e => setNxtd2( e.currentTarget.value||undefined ) } />
                </InputLine>
                <InputLine label={`(提示)监察没有该单元:`}>
                  <CheckSwitch checked={edt.ninsp || false} readOnly={true} onChange={e => 0} />
                </InputLine>
              </LineColumn>

            <br/>
              {/*<Button size="lg" intent="primary"
                iconAfter={<IconArrowRight />}
                onPress={ async () => {
                  await confirmation();
                } }
              > 确认修改检查
              </Button>*/}
              <Button size="lg" intent="primary"  iconAfter={<IconArrowRight />}
                      css={{ marginTop: theme.spaces.sm }}
                      onPress={ async () => {
                        const eqpNew=await confirmation();
                        await mutationFunc(eqpNew);
                      } }
              > 确认修改检查并保存到后端
              </Button>
            </div>
          </Container>
        </div>
      </div>

    </div>
  );
};

